<?php

namespace app\admin\controller\task;

use app\common\controller\Backend;
use app\admin\model\Task;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;
use think\Request;

/**
 * 呼叫任务明细管理
 *
 * @icon fa fa-circle-o
 */
class Job extends Backend
{

    /**
     * TaskJob模型对象
     * @var \app\admin\model\TaskJob
     */
    protected $model = null;

    protected $dataLimit = 'auth';

    protected $multiFields = '';

    protected $searchFields = 'number,name';
    protected $noNeedRight = ['getjson'];
    protected $noNeedLogin = ['update_all_task_job_grade', 'update_task_job_grade'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('TaskJob');
        $this->view->assign("calledList", $this->model->getCalledList());
        $this->view->assign("callstateList", $this->model->getCallstateList());
        $this->view->assign("ivrstateList", $this->model->getIvrstateList());
        $this->view->assign("queuestateList", $this->model->getQueuestateList());
    }

    public function detail($ids)
    {
        //$url=str_replace('/usr/share/nginx/html/public', 'https://rebot.oss-cn-hangzhou.aliyuncs.com', $this->model::get($ids)->record_path);
        //$url=str_replace('/tmp/rebot', 'https://rebot.oss-cn-hangzhou.aliyuncs.com', $url);
        $url=str_replace('/usr/share/nginx/html/public', 'https://data.vanxtec.com', $this->model::get($ids)->record_path);
        $url=str_replace('/tmp/rebot', 'https://data.vanxtec.com', $url);
        $this->view->assign('file', $url);
        $this->view->assign('job_id', $ids);
        return $this->fetch('detail');
    }


    //千万不要改动
    public function getjson($ids)
    {
        $path = Env::get('speech_script_output_path', '') . '/' . $ids . '.json';
        if (file_exists($path)) {
            $json_str = file_get_contents($path);
        } else {
            $json_str = 'error';
        }
        return $json_str;
    }

    private function load_task_job_detail_json($job_id)
    {
        if (Db::name('task_job_detail')->where('task_job_id', $job_id)->count() == 0) {
            $path = Env::get('speech_script_output_path', '') . '/' . $job_id . '.json';
            if (file_exists($path)) {
                $json_str = file_get_contents($path);
                $data = json_decode($json_str, true);
                foreach ($data['flow_result'] as $d) {
                    $value = array('task_job_id' => $job_id,
                        'type' => $d['type'],
                        'flow_name' => $d['flow_name'],
                        'hint' => is_null($d['voice']['hint']) ? " " : $d['voice']['hint'],
                        'path' => array_key_exists('path', $d['voice']) == null ? "" : $d['voice']['path'],
                        'addtime' => $d['voice']['time']);
                    if (Db::name('task_job_detail')->where($value)->count() == 0) {
                        Db::name('task_job_detail')->insert($value);
                    }
                }
            }
        }
    }

    private function count_task_faq_num($job_id)
    {
        $num = 0;
        $task_id = Db::name('task_job')->where('id', $job_id)->value('tid');
        $speech_id = Db::name('task')->where('id', $task_id)->value('speech_id');
        $keywords = Db::name('speech_faq')->where('speech_id', $speech_id)->where('important', 1)->column('keyword');
        $faqs = Db::name('task_job_detail')->where('task_job_id', $job_id)
            ->where('type', 'human')->where('flow_name', 'faq')->select();
        foreach ($faqs as $faq) {
            $hint = $faq['hint'];
            foreach ($keywords as $keyword) {
                $keys = explode(',', $keyword);
                foreach ($keys as $key) {
//                    var_dump($key);
                    if ($key != '') {
                        if (strstr($hint, $key)) {
                            $num += 1;
                            break;
                        }
                    }
                }

            }
        }
        return $num;
    }


    public function send_wechat($job_id)
    {

        $wechat = new \app\admin\controller\wechat\Index();

        $totalWx = Db::name('task_wx')
            ->alias('w')
            ->join('task_job j', 'j.tid = w.tid')
            ->join('task t', 'w.tid = t.id ')
            ->join('speech_faq f', 'j.faqnum = f.id', 'left')
            ->where('j.id', $job_id)
            ->field('w.openid,t.name as task_name,j.name,j.number,j.record_path,f.keyword')
            ->find();


        if ($totalWx) {
            $url=str_replace('/usr/share/nginx/html/public', 'http://data.vanxtec.com', $totalWx['record_path']);
            $url=str_replace('/tmp/rebot', 'https://data.vanxtec.com', $url);
            if ($wechat->sendMsg($totalWx['openid'], $totalWx['name'], "A类客户", $totalWx['number'], $totalWx['task_name'], $url, $totalWx['keyword'])) {
                Log::info('推送微信消息，job_id:' . $job_id . '客户电话：' . $totalWx['number']);
            }
        }

    }

    private function count_task_job_detail($job_id)
    {
//        echo $job_id."</br>";
        if (Db::name('task_job_detail')->where('task_job_id', $job_id)->count() > 0) {
            $routernum = Db::name('task_job_detail')->where('task_job_id', $job_id)->count();
            $humannum = Db::name('task_job_detail')->where('task_job_id', $job_id)->where('type', 'human')->count();
            $faqnum = $this->count_task_faq_num($job_id);
            $taskcalltime = Db::name('task_job_detail')->where('task_job_id', $job_id)->max('addtime') -
                Db::name('task_job_detail')->where('task_job_id', $job_id)->min('addtime');
            $task_id = Db::name('task_job')->where('id', $job_id)->value('tid');
            //如果客户不说话，直接评级为D
            if ($humannum == 0) {
                $grade = "D";
            } else {
                $grade = $this->set_grade($task_id, $taskcalltime, $faqnum);
            }

            if ($grade == 'A') {
                $this->send_wechat($job_id);
            }
            Db::name('task_job')->where('id', $job_id)->update(
                array("routernum" => $routernum,
                    "faqnum" => $faqnum,
                    "taskcalltime" => $taskcalltime,
                    "grade" => $grade,
                    'count_status' => '1'
                ));
        } else {
            Db::name('task_job')->where('id', $job_id)->update(
                array("routernum" => 0,
                    "faqnum" => 0,
                    "taskcalltime" => 0,
                    "grade" => 'D',
                    'count_status' => '1'
                ));
        }
    }

    public function update_all_task_job_grade()
    {
        $ids = Db::name('task_job')
            ->where('callstate', 'success')
            ->where('count_status', '0')
//            ->where('unix_timestamp()-updatetime', '>', 300)
            ->where('updatetime', '<', time() - 300)
            ->order('updatetime desc')
//            ->limit(10)
            ->column('id');
//        var_dump(Db::name('task_job')->getLastSql());
        foreach ($ids as $id) {
            $this->update_task_job_grade($id);
        }

    }

//    private function update_task_job_grade($job_id)
//    {
//        if (Db::name('task_job')->where('id', $job_id)->value('count_status') == '0') {
//            $this->load_task_job_detail_json($job_id);
//            $this->count_task_job_detail($job_id);
//        }
//    }


    private function update_task_job_grade($job_id)
    {
        $this->load_task_job_detail_json($job_id);
        $this->count_task_job_detail($job_id);
    }

    private function set_grade($task_id, $taskcalltime, $faqnum)
    {
//        var_dump($task_id);
        $val = "D";
        try {
            $speech_id = Db::name('task')->where('id', $task_id)->value('speech_id');
            $grades = Db::name('speech_grade')->where('speech_id', $speech_id)->select();
            if ($grades == null) {
                $grade = new \app\admin\controller\speech\Grade();
                $grade->init($speech_id);
                $grades = Db::name('speech_grade')->where('speech_id', $speech_id)->select();
            }
            $vals = array();
            foreach ($grades as $grade) {
                $vals[$grade['name']] = ['calltime' => $grade['calltime'], 'faqnum' => $grade['faqnum']];
            }
            if (($vals['C类客户']['calltime'] > 0 and $taskcalltime >= $vals['C类客户']['calltime'])
                or ($vals['C类客户']['faqnum'] > 0 and $faqnum >= $vals['C类客户']['faqnum'])) {
                $val = "C";
            }
            if (($vals['B类客户']['calltime'] > 0 and $taskcalltime >= $vals['B类客户']['calltime'])
                or ($vals['B类客户']['faqnum'] > 0 and $faqnum >= $vals['B类客户']['faqnum'])) {
                $val = "B";
            }
            if (($vals['A类客户']['calltime'] > 0 and $taskcalltime >= $vals['A类客户']['calltime'])
                or ($vals['A类客户']['faqnum'] > 0 and $faqnum >= $vals['A类客户']['faqnum'])) {
                $val = "A";
            }
        } catch (Exception $e) {
            ;
        }
        return $val;
    }

    private function get_grade_where($grade)
    {

//        $where['callstate'] = ['=', 'success'];
        $where['callstate'] = ['<>', 'none'];
//        if ($grade == "a") {
//            $where['grade'] = ['=', 'A'];
//        } elseif ($grade == 'b') {
//            $where['grade'] = ['=', 'B'];
//        } elseif ($grade == 'c') {
//            $where['grade'] = ['=', 'C'];
//        } elseif ($grade == 'd') {
//            $where['grade'] = ['=', 'D'];
//        } else {
////                $where['grade'] = ['in', '("A","B","C","D")'];
//        }

        return $where;
    }

    /**
     * 查看
     */
    public function index($ids = NULL, $grade = 'all')
    {
        $tid = $ids;
        if ($tid) {
            $row = Task::get($tid);
            if ($row) {
                $adminIds = $this->getDataLimitAdminIds();
                if (is_array($adminIds)) {
                    if (!in_array($row[$this->dataLimitField], $adminIds)) {
                        $this->error(__('You have no permission'));
                    }
                }
                $tid = $row['id'];
            } else {
                $this->error(__('No Results were found'));
            }
        }
        $this->view->assign('taskId', $tid);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where2 = array();
            if ($tid) {
                $where2['tid'] = array('=', $tid);
            }
            $total = $this->model
                ->with('admin,task')
                ->where($where)
                ->where($where2)
                ->where($this->get_grade_where($grade))
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('admin,task')
                ->where($where)
                ->where($where2)
                ->where($this->get_grade_where($grade))
                ->order('calltime', 'desc')
                ->limit($offset, $limit)
                ->select();

//            var_dump($list[0]);

            foreach ($list as $row) {
                $row->getRelation('admin')->visible(['nickname']);
                $row->getRelation('task')->visible(['name']);
            }
            $list = collection($list)->toArray();


            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        $this->error(__('You have no permission'));
    }

    public function edit($ids = NULL)
    {
        $this->error(__('You have no permission'));
    }

    public function del($ids = "")
    {
        $this->error(__('You have no permission'));
    }

    public function multi($ids = "")
    {
        $this->error(__('You have no permission'));
    }

    /**
     * 导入
     */
    protected function import()
    {
        $tid = $this->request->param("tid");
        $tid = NULL;
        if (!$tid) {
            $this->error(__('No Results were found'));
        } else {
            $row = Task::get($tid);
            if ($row) {
                $adminIds = $this->getDataLimitAdminIds();
                if (is_array($adminIds)) {
                    if (!in_array($row[$this->dataLimitField], $adminIds)) {
                        $this->error(__('You have no permission'));
                    }
                }
                $tid = $row['id'];
            } else {
                $this->error(__('No Results were found'));
            }
        }
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        /*
        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v)
        {
            if ($importHeadType == 'comment')
            {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            }
            else
            {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }
        */
        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[$currentColumn] = $val;
            }
        }
        $template_fields = array('呼叫号码', '客户名称');
        $fields = array_intersect($fields, $template_fields);
        if (count($fields) < count($template_fields)) {
            $this->error(__('导入的表格字段有误，<br />必须含有 [呼叫号码] 和 [客户名称] 两列'));
        }
        $insert = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            //for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++)
            foreach ($fields as $k => $v) {
                $val = $currentSheet->getCellByColumnAndRow($k, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            $row['number'] = $temp['呼叫号码'];
            $row['name'] = $temp['客户名称'];
            $row['admin_id'] = $this->auth->id;
            $row['tid'] = $tid;

            if ($row) {
                $insert[] = $row;
            }
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        try {
            $this->model->saveAll($insert);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }

        $this->success();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 行内编辑
     */
    public function line_edit()
    {
        $request= Request::instance();
        $id         = $request->get('id');//明细id
        $content    = $request->get('content');
        $action     = $request->get('action');

        if(!$id){
            return json(['code'=>0,'msg'=>'系统错误']);
        }

        $checkInfo = Db::name('task_job')->where('id',$id)->find();
        if(!$checkInfo){
            return json(['code'=>1,'msg'=>'任务不存在']);
        }

        if(isset($content)){
            Db::name('task_job')
                ->where('id',$id)
                ->update(['content'=> $content]);
        }
        if(isset($action)){
            Db::name('task_job')
                ->where('id',$id)
                ->update(['read_status'=> 1]);
        }

        return json(['code'=>200,'msg'=>'执行成功']);

    }

}
